<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :default-config="toolbarConfig" />
    <Editor
      v-model="data.content"
      style="height: 350px; overflow-y: hidden"
      :default-config="editorConfig"
      @on-created="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IToolbarConfig, IEditorConfig } from "@wangeditor/editor";
type InsertFnType = (url: string, alt: string, href: string) => void;

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {
        content: "",
        id: "",
      };
    },
  },
});

const { data } = toRefs(props);

const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload-img`);
const editorConfig: Partial<IEditorConfig> = {
  MENU_CONF: {
    uploadImage: {
      fieldName: "wangeditor-uploaded-image",
      allowedFileTypes: ["image/jpeg", "image/png"],
      meta: {
        guid: data.value.id,
      },
      metaWithUrl: true,
      withCredentials: true,
      server: actionUrl.value,
      maxFileSize: 10 * 1024 * 1024, // 10M
      base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb
      // 自定义插入图片
      customInsert(res: any, insertFn: InsertFnType) {
        console.log(res);
        if (res.type === 0) {
          if (res.success) {
            insertFn(import.meta.env.VITE_APP_BASE_API + res.data.url, res.data.alt, "");
          } else {
          }
        } else {
        }
        return true;
      },
    },
  },
};
// 内容 HTML
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: ["group-video", "fullScreen"],
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  editor.focus();
};
</script>

<style scoped>
#editor—wrapper {
  border: 1px solid #ccc;
  z-index: 100; /* 按需定义 */
}
</style>
